<template>
    <div class="data_auth_container">
        <div class="btn_area">
            <el-form :inline="true" :model="batchForm" class="demo-form-inline">
                <el-form-item label-width="0px">
                    <el-checkbox v-model="batchForm.batch">批量设置</el-checkbox>
                </el-form-item>
                <template v-if="batchForm.batch">
                    <el-form-item label="控制模式">
                        <el-select v-model="batchForm.auth_mode">
                            <el-option label="创建者" value="creator" />
                            <el-option label="部门" value="group" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门" v-if="batchForm.auth_mode === 'group'">
                        <tree-select v-bind.sync="treeOptions" @input="handleTreeSelectInput"
                                     style="width: 190px;" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleConfirmBatch">确定</el-button>
                    </el-form-item>
                </template>
            </el-form>
        </div>
        <vxe-table-template :data="dataList" :options.sync="tableOptions" @event="handleTableEvent" />
    </div>
</template>

<script>
import {mapState} from "vuex";

export default {
    name: "DataAuth",
    props: {
        authType: {
            type: String,
            default: 'row',
        },
        type: {
            type: String,
            default: 'user',
        },
        row: {
            type: Object,
            default: null,
        },
    },
    data () {
        const _this = this;
        return {
            groupTree: [],
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: "DataAuthTable",
                container: ".data_auth_container",
                multiSelect: true,
                columns: [
                    {
                        label: "所属模块",
                        prop: "application",
                        align: "center",
                        formatter(row) {
                            let filter = _this.appList.filter(item => item.code === row.application);
                            if (_this.$utils.isNotEmptyList(filter)) {
                                return filter[0].name;
                            }
                            return '';
                        },
                    },
                    {
                        label: "功能编码",
                        prop: "code",
                        align: "center",
                    },
                    {
                        label: "功能名称",
                        prop: "name",
                        align: "center",
                    },
                    {
                        label: "授权模式",
                        prop: "auth_mode",
                        align: "center",
                        width: 100,
                        editRender: {
                            name: 'CustomSelect',
                            props: {
                                filterable: true,
                                defaultFirstOption: true,
                                options: [
                                    {
                                        value: 'creator',
                                        label: '创建者',

                                    },
                                    {
                                        value: 'group',
                                        label: '部门',
                                    },
                                ],
                            },
                        },
                    },
                    {
                        label: "部门",
                        prop: "groups",
                        align: "center",
                        width: 200,
                        editRender: {
                            name: 'CustomTreeSelect',
                            props: {
                                multiple: true,
                                flat: true,
                                limit: 1,
                                limitText(count) {
                                    return count;
                                },
                                valueFormat: 'object',
                                defaultExpandLevel: Infinity,
                            },
                            optionsFn(row) {
                                return _this.groupTree;
                            },
                            filter(row) {
                                return row.auth_mode === 'group';
                            },
                            formatter({ row }) {
                                if (row.auth_mode !== 'group') {
                                    return '';
                                }
                                let list = (row.group_list || []).map(item => item.auth_group_name);
                                return list.join('、');
                            },
                            events: {
                                input({ row }, data) {
                                    let group_list = (data.value || []).map(item => {
                                        let obj = {
                                            auth_group_sid: item.id,
                                            auth_group_name: item.label,
                                        };
                                        let filter = (row.group_list || []).filter(t => t.auth_group_sid === item.id);
                                        if (_this.$utils.isNotEmptyList(filter)) {
                                            obj.id = filter[0].id;
                                            obj.sid = filter[0].sid;
                                        }
                                        return obj;
                                    });
                                    _this.$set(row, 'groups', data.value);
                                    _this.$set(row, 'group_list', group_list);
                                },
                            },
                        },
                    },
                ],
                pagination: false,
                getMaxHeight() {
                    return $(_this.getActiveTabsContainer()).height() * 0.8;
                },
            },
            batchForm: {
                batch: false,
                auth_mode: 'creator',
                group_list: [],
            },
            treeOptions: {
                zIndex: 9999,
                clearValueText: '清除值',
                multiple: true,
                flat: true,
                limit: 1,
                limitText(count) {
                    return count;
                },
                valueFormat: 'object',
                defaultExpandLevel: Infinity,
                options: [],
            },
        };
    },
    computed: {
        ...mapState(["menus"]),
        appList() {
            return (this.menus || []).filter(item => item.res_type === 'application');
        },
    },
    watch: {
        row: {
            handler () {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init () {
            const _this = this;
            if (!_this.row) {
                return;
            }
            await _this.initGroupTree();
            _this.initDataAuthList();
            let group_list = [];
            if (_this.$utils.isNotEmpty(_this.row.person_group_sid)) {
                group_list.push({
                    id: _this.row.person_group_sid,
                    label: _this.row.person_group_name,
                });
            }
            _this.batchForm = $.extend({}, _this.batchForm, {
                batch: false,
                auth_mode: 'creator',
                group_list,
            });
            _this.treeOptions = $.extend({}, _this.treeOptions, {
                value: group_list,
            });
        },
        initGroupTree() {
            const _this = this;
            _this.groupTree = [];
            return _this.fetchData(_this.$api.API_FindSysGroupTreeAll).then(result => {
                _this.groupTree = _this.transferData(result.data);
                _this.treeOptions = $.extend({}, _this.treeOptions, {
                    options: _this.groupTree.map(item => $.extend({}, item)),
                });
            });
        },
        handleTreeSelectInput(val) {
            this.batchForm = $.extend({}, this.batchForm, {
                group_list: val,
            });
        },
        transferData(data) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(data)) {
                data.forEach(item => {
                    let obj = {};
                    obj.id = item.sid;
                    obj.label = item.name;
                    if (_this.$utils.isNotEmptyList(item.childrens)) {
                        obj.children = _this.transferData(item.childrens);
                    }
                    if (_this.$utils.isNotEmpty(_this.row.person_group_sid) && item.sid === _this.row.person_group_sid) {
                        obj.isDisabled = true;
                    }
                    list.push(obj);
                });
            }
            return list;
        },
        initDataAuthList() {
            const _this = this;
            _this.dataList = [];
            return _this.fetchData(_this.$api.API_FindSysDataAuths4User, {
                auth_type: _this.authType,
                user_sid: _this.row.sid,
                type: _this.type,
            }).then(result => {
                let list = (result.data || []).map(item => {
                    let obj = $.extend({}, item);
                    let group_list = (item.group_list || []).map(t => $.extend({}, t));
                    let groups = group_list.map(t => {
                        return {
                            id: t.auth_group_sid,
                            label: t.auth_group_name,
                        };
                    });
                    if (_this.$utils.isNotEmpty(_this.row.person_group_sid) && _this.row.person_group_sid !== '-1') {
                        groups.unshift({
                            id: _this.row.person_group_sid,
                            label: _this.row.person_group_name,
                        });
                        group_list.unshift({
                            auth_group_sid: _this.row.person_group_sid,
                            auth_group_name: _this.row.person_group_name,
                            user_group: true,
                        });
                    }
                    obj.groups = groups;
                    obj.group_list = group_list;
                    return obj;
                });
                _this.dataList = _this.resetIndex(list);
            });
        },
        handleTableEvent(event) {
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        handleConfirmBatch() {
            const _this = this;
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            let list = [];
            _this.dataList.forEach(item => {
                let obj = $.extend({}, item);
                let filter = _this.selectionList.filter(t => t._index === item._index);
                if (_this.$utils.isNotEmptyList(filter)) {
                    obj.auth_mode = _this.batchForm.auth_mode;
                    obj.group_list = _this.batchForm.group_list.map(t => {
                        return {
                            auth_group_sid: t.id,
                            auth_group_name: t.label,
                        };
                    });
                    obj.groups = _this.batchForm.group_list.map(t => $.extend({}, t));
                }
                list.push(obj);
            });
            _this.dataList = _this.resetIndex(list);
        },
        async confirm() {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(_this.dataList)) {
                _this.$message.info('数据授权为空');
                return false;
            }
            let subData = _this.dataList.map(item => {
                let obj = $.extend({}, item);
                delete obj._X_ROW_KEY;
                delete obj.groups;
                if (item.auth_mode !== 'group') {
                    delete obj.group_list;
                } else {
                    obj.group_list = (obj.group_list || []).filter(t => t.auth_group_sid !== _this.row.person_group_sid);
                }
                return obj;
            });
            return _this.fetchData(_this.$api.API_BathSaveSysDataAuth, {
                list: subData,
            }).then(() => {
                _this.$message.success('授权成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.data_auth_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .btn_area {
        /deep/.vue-treeselect__control {
            height: 24px;

            .vue-treeselect__placeholder {
                line-height: 24px;
            }

            .vue-treeselect__single-value {
                line-height: 24px;
            }

            .vue-treeselect__input {
                height: 24px;
                line-height: 24px;
            }

            .vue-treeselect__multi-value {
                margin-bottom: 0;
                height: 24px;

                .vue-treeselect__input-container {
                    padding: 0;

                    .vue-treeselect__input {
                        height: 16px !important;
                    }
                }

                .vue-treeselect__limit-tip {
                    padding: 0;
                    line-height: 18px;
                }

                .vue-treeselect__multi-value-item-container {
                    padding: 0;

                    .vue-treeselect__multi-value-item {
                        line-height: 16px;
                    }
                }
            }
        }
    }
}
</style>

